﻿#region Copyright 
/*-------------------------------------------------------------------------
* 命名空间名称/文件名:    SSPivot.Authorization.User/CurrentUserExtensions 
* CLR版本:     4.0.30319.42000
* 机器名称:    DESKTOP-NHMLO8A
* 功 能：       N/A
* 类 名：       CurrentUserExtensions
* 创建时间：  2025/5/24 10:37:24
* 版本号：      v1.0
* 创建人:        xulong
*-------------------------------------------------------------------------*/
#endregion
using JetBrains.Annotations;
using SSPivot.AspNetCore.Abstractions.User;
using SSPivot.Authorization.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SSPivot.Authorization.User
{
    public static class CurrentUserExtensions
    {
        public static string FindClaimValue(this ICurrentUser currentUser, string claimType)
        {
            return currentUser.FindClaim(claimType)?.Value;
        }

        public static T FindClaimValue<T>(this ICurrentUser currentUser, string claimType)
        {
            var value = currentUser.FindClaimValue(claimType);
            if (value == null)
            {
                return default;
            }
            return value.To<T>();
        }

        public static long? GetId(this ICurrentUser currentUser)
        {
            return currentUser?.Id;
        }

        public static Guid? FindImpersonatorTenantId([NotNull] this ICurrentUser currentUser)
        {
            var impersonatorTenantId = currentUser.FindClaimValue(SSPivotClaimTypes.ImpersonatorTenantId);
            if (impersonatorTenantId == null || impersonatorTenantId.IsNullOrWhiteSpace())
            {
                return null;
            }
            if (Guid.TryParse(impersonatorTenantId, out var guid))
            {
                return guid;
            }

            return null;
        }

        public static Guid? FindImpersonatorUserId([NotNull] this ICurrentUser currentUser)
        {
            var impersonatorUserId = currentUser.FindClaimValue(SSPivotClaimTypes.ImpersonatorUserId);
            if (impersonatorUserId == null || impersonatorUserId.IsNullOrWhiteSpace())
            {
                return null;
            }
            if (Guid.TryParse(impersonatorUserId, out var guid))
            {
                return guid;
            }

            return null;
        }
    }
}
